package com.chenshu.intercept_demo.interceptors;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-04-22
 * Time：22:52
 */

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    //只封装非HashMap对象
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return !returnType.getParameterType().equals(HashMap.class);
    }

    //处理统一数据返回格式的逻辑
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HashMap<String, Object> retMap = new HashMap<>();
        retMap.put("code", "200");
        retMap.put("msg", "");
        retMap.put("body", body);

        if (body instanceof String) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.writeValueAsString(retMap);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return retMap;
    }
}
